<?php
declare (strict_types = 1);

namespace app\controller;

use app\business\CheckCode;
use app\lib\JWT;
use app\lib\Msg;
use Mrwanghongda\SmsSdk\Sms\SmsFactory;
use think\db\exception\DbEventException;
use think\Request;

class Login
{
//    手机号密码登录
    public function telPwd(Request $request){
        $postData=$request->param();
        try {
            $checkData=\app\model\Login::telPwd($postData['tel']);
            if(!$checkData){
                return fail('手机号错误');
            }
            if($checkData['password']!=$postData['password']){
                return fail('密码错误');
            }
            session('id',$checkData['id']);
            $token=Jwt::createjwt($checkData['id']);
            $data=[
                'tel'=>$checkData['tel'],
                'password'=>$postData['password'],
                'token'=>$token,
            ];
            return success($data,200,'登录成功');
        }catch (DbEventException $exception){
            return fail('数据库异常');
        }
    }
//发送验证码
    function getPhone(Request $request){
        $postData=$request->param();
        $checkData=\app\model\Login::searchPwd($postData['tel']);
        if(!$checkData){
            return fail('手机号不存在');
        }
        $tel=$request->get('tel');
        $code=CheckCode::getCode($tel);
        if(!$code){
            return fail("短信发送频繁");
        }
        $result=Msg::getPhone($tel);
        return $result;
    }
    //验证验证码
    function telData(Request $request){
        $postData=$request->param();
        try {
            $checkData=\app\model\Login::searchPwd($postData['tel']);
            if(!$checkData){
                return fail('手机号不存在');
            }
            $code=CheckCode::checkCode($postData['tel'],$postData['code']);
            return $code;
        }catch (DbEventException $exception){
            return fail('数据库异常');
        }
    }
    //修改密码
    function updatePwd(Request $request){
        $postData=$request->post();
        try {
            $checkData=\app\model\Login::searchPwd($postData['tel']);
            if(!$checkData){
                return fail('手机号不存在');
            }
            if($checkData['password']!=$postData['password']){
                return fail('原密码错误');
            }
            $updateData=\app\model\Login::updatePwd($postData,$postData['tel']);
            return success($updateData,200,'修改密码成功');
        }catch (DbEventException $exception){
            return fail('数据库异常');
        }
    }
}
